package org.lucava.boatskeeper.client.presenter;

import org.lucava.boatskeeper.client.BoatsKeeperServiceAsync;
import org.lucava.boatskeeper.client.event.user.EditUserCancelledEvent;
import org.lucava.boatskeeper.client.event.user.UserUpdatedEvent;
import org.lucava.boatskeeper.shared.User;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HasValue;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;

public class EditUserPresenter implements Presenter {
	public interface Display {
		HasClickHandlers getSaveButton();

		HasClickHandlers getCancelButton();

		HasValue<String> getUserName();

		HasValue<String> getRights();

		Widget asWidget();

	}

	private User mUser;
	private final BoatsKeeperServiceAsync mRpcService;
	private final HandlerManager mEventBus;
	private final Display mDisplay;

	public EditUserPresenter(BoatsKeeperServiceAsync rpcService,
			HandlerManager eventBus, Display display) {
		this.mRpcService = rpcService;
		this.mEventBus = eventBus;
		this.mUser = new User();
		this.mDisplay = display;
		bind();
	}

	public EditUserPresenter(BoatsKeeperServiceAsync rpcService,
			HandlerManager eventBus, Display display, Integer id) {
		this.mRpcService = rpcService;
		this.mEventBus = eventBus;
		this.mDisplay = display;
		bind();

		rpcService.getUser(id, new AsyncCallback<User>() {
			public void onSuccess(User result) {
				System.out.println(result);
				if (result != null) {
					mUser = result;
					EditUserPresenter.this.mDisplay.getUserName().setValue(
							mUser.getName());
					EditUserPresenter.this.mDisplay.getRights().setValue(
							mUser.getRights());
				}
			}

			public void onFailure(Throwable caught) {
				Window.alert("Error retrieving User");
			}
		});

	}

	public void bind() {
		this.mDisplay.getSaveButton().addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				doSave();
			}
		});

		this.mDisplay.getCancelButton().addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				mEventBus.fireEvent(new EditUserCancelledEvent());
			}
		});
	}

	public void go(final HasWidgets container) {
		container.clear();
		container.add(mDisplay.asWidget());
	}

	private void doSave() {
		mUser.setName(mDisplay.getUserName().getValue());
		mUser.setRights(mDisplay.getRights().getValue());

		mRpcService.updateUser(mUser, new AsyncCallback<User>() {
			public void onSuccess(User result) {
				mEventBus.fireEvent(new UserUpdatedEvent(result));
			}

			public void onFailure(Throwable caught) {
				Window.alert("Error updating User!");
			}
		});
	}

}
